
var appkey = 'p5tvi9dspqkw4';
RongIMLib.RongIMClient.init('p5tvi9dspqkw4');



//var token = "";//注册时的token
var token = localStorage.getItem('rongToken');

RongIMClient.connect(token, {
    onSuccess: function(userId) {
        console.log( userId);
    },
    onTokenIncorrect: function() {
        console.log('token 无效');
    },
    onError: function(errorCode){
        var info = '';
        switch (errorCode) {
            case RongIMLib.ErrorCode.TIMEOUT:
                info = '超时';
                break;
            case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
                info = '不可接受的协议版本';
                break;
            case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                info = 'appkey不正确';
                break;
            case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                info = '服务器不可用';
                break;
        }
        console.log(info);
    }
});

// 连接状态监听器
RongIMClient.setConnectionStatusListener({
    onChanged: function (status) {
        // status 标识当前连接状态
        switch (status) {
            case RongIMLib.ConnectionStatus.CONNECTED:
                console.log('链接成功');
                break;
            case RongIMLib.ConnectionStatus.CONNECTING:
                console.log('正在链接');
                break;
            case RongIMLib.ConnectionStatus.DISCONNECTED:
                console.log('断开连接');
                break;
            case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                console.log('其他设备登录');
                break;
            case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                console.log('域名不正确');
                break;
            case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                console.log('网络不可用');
                break;
        }
    }
});

 // 接收消息
		RongIMClient.setOnReceiveMessageListener({
			// 接收到的消息
			onReceived: function (message) {
			    // 判断消息类型
//			    console.log(message)
				console.log("新消息: " + message.targetId);
				
				//type_xt 为2有好友申请   type为1是系统消息
				var type_xt = message.content.extra
				if(!type_xt || type_xt=="undefined" || type_xt=="null"){
					type_xt = ''
				}
//				console.log(type_xt)
				if(type_xt!=''){
					if(type_xt.type){
						var html_xt='';
						switch (type_xt.type){
							case 2:
							html_xt+='<dl class="clearfix msg_left ">'+
										'<dt class="left"><img class="msg_head" src="img/icon_cx.png"/></dt>'+
										'<dd class="left">'+
											'<div class="msg_box relative">'+
												'<i class="absolute"></i>'+
												'<span class="msg_font">'+ message.content.content +'</span>'+
											'</div>'+
										'</dd>'+
									'</dl>'
									$('.room_main').append(html_xt)
								break;
							case 1:
							
								break;	
							default:
								break;
						}
					}
					
			   }else{
				if(message.conversationType==1){//单聊
//					
					if(friend_id_active == message.targetId){
						var head=$('.friends_list li.active').children('dl').find('dt').find('.friends_head').attr('src')
						var html_friend='';
						//文本
					    if(message.content.messageName =='TextMessage'){
					    	html_friend += '<div class="room_left room_list mg_top15"><p class="text-center color_55 mg_tb10">下午1：52</p>'+
								   		'<div class="room_info flex">'+
								   			'<img class="room_head" src="'+head+'"/>'+
								   			'<span class="room_text">'+RongIMLib.RongIMEmoji.emojiToHTML(message.content.content)+'</span>'+
								   		'</div>'+
								   		'</div>'
					    	
					    }else if(message.content.messageName == 'ImageMessage'){//图片
					    	html_friend +='<div class="room_left room_list mg_top15"><p class="text-center color_55 mg_tb10">下午1：52</p>'+
								   		'<div class="room_info flex">'+
								   			'<img class="room_head" src="'+head+'"/>'+
								   			'<span class="room_text">'+message.content.imageUri+'</span>'+
								   		'</div>'+
								   		'</div>'
					    	
					    	
					    	
					    }else if(message.content.messageName =='VoiceMessage'){//语音
					    	html_friend +='<p class="text-center color_9 padding_tb10">收到语音 请在手机上查看</p>'
					    	
//					    	var audioFile =message.content.content
//					    	var duration = audioFile.length / 1024;
//// 预加载                                            
//							RongIMLib.RongIMVoice.preLoaded(audioFile, function(){
//							    // 播放声音
//							    RongIMLib.RongIMVoice.play(audioFile, duration);
//							});
					    }
					    $('.room_main').append(html_friend)
					}else{
						$.each(friend_list, function() {
							if($(this).attr('data-friendid')==message.targetId){
							   var count = getnews(message.targetId,message.conversationType)
//							   
							}
						});
						$('.room_main ').append(html_friend)
					}
				
				   
				}
			
	        }

			}
		});
		
		
		
     //发送信息 单聊
     var msglist={},msgarr=[]
    function sendMessage(id,head) {
    	console.log(id)
    	console.log(head)
    	var msg = $("#sedmsg").html()
    	if(!msg){
    		alert('不能发空的')
    		return false;
    	}
    	msg = RongIMLib.RongIMEmoji.symbolToEmoji(msg);
    	console.log(msg)
    	var msg1 = new RongIMLib.TextMessage({ content: msg,} );
		var targetId = id
    	if(targetId=''){
    		msg("请选择聊天对象")
    		return false;
    	}
    	var conversationType = RongIMLib.ConversationType.PRIVATE			
        RongIMClient.getInstance().sendMessage(conversationType, targetId, msg1, {
            // 发送消息成功
            onSuccess: function (message) {
         		 $("#sedmsg").html('')
//	            		var extra = eval('(' + message.content.extra + ')');
	                var str='<div class="room_right room_list mg_top15"><div class="room_info flex mg_top15">' +
				   			'<span class="room_text">'+ RongIMLib.RongIMEmoji.emojiToHTML(message.content.content)+'</span>' +
				   			'<img class="room_head" src="'+head+'">' +
				   		'</div>'+	
				   		'</div>'	
	                
	                $('.room_main').append(str);
	                
	                msglist.id=id,
	                msglist.head=head,
	                msglist.content=RongIMLib.RongIMEmoji.emojiToHTML(message.content.content)
	               
	                console.log(msglist)
	                msgarr.push(msglist)
	               console.log(msgarr)
	               window.localStorage.setItem('msgarr', JSON.stringify(msgarr));
//	                $('.room_main').scrollTop($('.msg_content')[0].scrollHeight);                             
            },
            onError: function (errorCode, message) {
                var info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    case 23408:
                        info = 23408;
                        break;
                    default:
                        info = "x";
                        break;
                }
                if (info == 23408){
                    layer.msg('您已被禁言,不能发送消息!', {icon: 0});
                }
//              console.log('发送失败:' + info);
                 msg('发送失败:' + info)
            }
        });
    }

	
    //发送图片
    function sendImg(type,url,sendData,head) {
//      console.log(sendData)
    	var msg = new RongIMLib.ImageMessage({content:sendData , imageUri: url,extra:{
    		head:head
    	}});
		if(type==1){
			var conversationType = RongIMLib.ConversationType.PRIVATE;
		}else if(type==3){
			var conversationType = RongIMLib.ConversationType.GROUP;
		}
		var targetId=7
//		console.log(targetId)
    	if(targetId=''){
    		msg("请选择聊天对象")
    		return false;
    	}
    				
        RongIMClient.getInstance().sendMessage(conversationType, '7', msg, {
            // 发送消息成功
            onSuccess: function (message) {
            	$('.add_more').hide(200)
 			    $('.add_more').removeClass('show')
         		 $("#sedmsg").html('')
//	            		var extra = eval('(' + message.content.extra + ')');
	                var str='<div class="room_right room_list mg_top15"><div class="room_info flex ">' +
				   			'<img class="room_img" src="'+message.content.imageUri+'"/>' +
				   			'<img class="room_head" src="'+message.content.extra.head+'">' +
				   		'</div>'+
	                '</div>'
	                
	                
	                $('.room_main ').append(str);
//	                $('.room_main ').scrollTop($('.msg_content')[0].scrollHeight);
                
               
            },
            onError: function (errorCode, message) {
                console.log('errorCode:'+errorCode);
                var info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    case 23408:
                        info = 23408;
                        break;
                    default:
                        info = "x";
                        break;
                }
                if (info == 23408){
                    layer.msg('您已被禁言,不能发送消息!', {icon: 0});
                }
                console.log('发送失败:' + info);
                msg('发送失败:' + info)
            }
        });
    }
   
 	//视频初始化
// 	var config = {
//	  timeout: 20000,
//	  RongIMLib: RongIMLib,
//	  RongRTC: RongRTC
//	};
//	var rongCallLib = RongCallLib.init(config);


//获取会话列表

//RongIMClient.getInstance().getConversationList({
//  onSuccess: function(list) {
//  	console.log(list)
//      // list => 会话列表集合
//  }, 
//  onError: function(error) {
//      // do something
//  }
//}, null);


